﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.IO;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

namespace Liebrand.UrlShortener
{
    public partial class UrlShortenerSettings : LayoutsPageBase
    {

        #region Declarations

        protected Button ButtonOk;
        protected WebApplicationSelector WebApplicationSelector;
        #endregion

        #region Methods

        protected void ButtonOk_Click(object sender, EventArgs e)
        {

            var farm = SPAdministrationWebApplication.Local;

            using (var site = farm.Sites[0])
            {
                using (var web = site.RootWeb)
                {

                    if (web.Properties.ContainsKey("LiebrandUrlShortener"))
                    {
                        var currentShortener = web.Properties["LiebrandUrlShortener"];
                        var currentWebApplication = SPWebApplication.Lookup(new Uri(currentShortener));
                        try
                        {
                            currentWebApplication.Features.Remove(new Guid("9B44F77A-41AA-4A6B-8B43-61DA567A5EAA"), true);
                        }
                        catch (Exception ex)
                        {
                        }

                        web.Properties.Remove("LiebrandUrlShortener");
                    }

                    var selectedWebApplication = WebApplicationSelector.CurrentItem;
                    selectedWebApplication.Features.Add(new Guid("9B44F77A-41AA-4A6B-8B43-61DA567A5EAA"), true);

                    var url = selectedWebApplication.AlternateUrls.Where(item => item.UrlZone.ToString().Equals("Default")).FirstOrDefault();
                    if (url == null)
                        throw new SPException("Unable to find default zone for the selected web application.");

                    web.Properties.Add("LiebrandUrlShortener", url.IncomingUrl);

                    web.Properties.Update();
                }
            }

        }
        #endregion

    }
}
